﻿using HCMS.CommonDtos;
using HCMS.Entities.OAuth2;
using HCMS.IRepositories.OAuth2;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;

namespace HCMS.Repositories.OAuth2
{
    /// <summary>
    /// OAuth 2.0 AccessToken 仓储层
    /// </summary>
    public class OAuth2AccessTokenRepository : OAuth2BaseRepository<OAuth2AccessToken>, IOAuth2AccessTokenRepository
    {
        public OAuth2AccessTokenRepository(IDbContextProvider<OAuth2DbContext> dbContextProvider)
                : base(dbContextProvider)
        {
        }

        /// <summary>
        /// 管理 列表
        /// </summary>
        /// <param name="searchArgs">搜索 参数</param>
        /// <param name="pager">分页 参数</param>
        /// <returns></returns>
        public async Task<ListPagerDto<OAuth2AccessToken>> ManageList(SearchArgsDto searchArgs, PagerArgsDto pager)
        {
            var query = await GetQueryableAsync();

            if (searchArgs.FromId > 0)
            {
                query = query.Where(t => t.AppId == searchArgs.FromId);
            }

            var count = await query.CountAsync();
            pager.RowCount = count;

            var list = new List<OAuth2AccessToken>();

            if (count > 0)
            {
                query = query.OrderByDescending(t => t.Id);

                list = await query
                           .Skip((pager.CurrentPageIndex - 1) * pager.PageSize)
                           .Take(pager.PageSize)
                           .ToListAsync();
            }

            var result = new ListPagerDto<OAuth2AccessToken>()
            {
                Data = list ?? new List<OAuth2AccessToken>(),
                PagerInfo = pager
            };

            return result;
        }
    }
}
